%% Input dataFolder and filenumbers containing evoked epscs from SJ "run experiment" macro (Random ISI from Lisi).
dataFolder='7_18_17_05';
fileNumbers=3:20;
stimInt=20;
nfiles=numel(fileNumbers);

path1='C:\Users\tomas\Documents\1. Harvard\2017 - Spring\Regehr lab rotation\Data\';
path2=['0' dataFolder(1:2) dataFolder(6:7) '\' dataFolder(1:7) '\' dataFolder '\'];


ISI=[10 20 50 100 200 500];

tracesMat= NaN( 170000,ceil(nfiles/numel(ISI)),numel(ISI));  %First dimension is .y, second dim is max number of trials per ISI, third is ISI.
tracesMatAll=NaN(170000,nfiles); %preallocate Matrix for all traces.
l=ones(numel(ISI),1); % ones vector for l(k)+1 storage of traces in correct column when classifying.
for j= 1:nfiles; % Read all files into structure IBW.
        
        
        IBW(j)= IBWread([path1 path2 'ch0_' num2str(fileNumbers(j)) '.ibw' ]);
        Dx=IBW(j).dx;  %take any IBW to find sampling rate.
        Fs=1/Dx;       
        tracesMatAll(1:numel(IBW(j).y),j) = IBW(j).y; %put all the .y in a 2D matrix.
        [pks, locs]= findpeaks(tracesMatAll(:,j),'minpeakheight',200) %Since all the trace is used, it may return 3 peaks, first one for capacitative transient, just use last 2 or specify index after cap transient.
        locs=locs(end-1:end);  %get rid of capacitative transient peaks, if they exist.
        
        
        %Create a loop that evaluates the current trace (j) and stores it
        %in the correct dimension for it's ISI in tracesMat. eg.
        %tracesMat(:,:,1)= all traces for ISI(1) i.e. 10 ms.
        for k=1:numel(ISI);
        if ((ISI(k)+2)/1e3 > (locs(2)-locs(1))*Dx) & ((ISI(k)-2)/1e3 < (locs(2)-locs(1))*Dx); % +-2ms error in stim artifact location allowed.
            tracesMat(1:numel(tracesMat(:,j),l(k),k))=tracesMatAll(:,j);
            l(k)=l(k)+1;
        else  % do nothing.
        end
        end
end

clear IBW; %release memory from all the IBW structures.

trials=1:ceil(nfiles/numel(ISI));
ISI=1:numel(ISI);
baselineMat(ISI,trials)=nanmean(tracesMat([baselineidx],trials,ISI)); %create baseline matrix for bsxfun @minus, rows are ISI, columns are trials.
tracesMatBS=bsxfun(@minus,tracesMat(:,trials,ISI),baselineMat(ISI,:); %idk if this is gonna work but i'm trying vectorized code.



